import { reactive, ref, watchEffect } from 'vue';
import { useMessage } from '@/hooks/useMessage';
import { editProductNum } from '@/apis/todo/flowBusiness';

export const useEditProductNum = (formNo: string, props: any) => {
  const { createMessage } = useMessage();
  const headerRightFormState = reactive({
    productNum: null as unknown as number,
    productUnit: ''
  });
  // 原始产物数量
  const sourceProductNum = ref();
  const sourceProductUnit = ref();
  watchEffect(() => {
    headerRightFormState.productNum = Number(props.supplierFormInfo?.productNum);
    sourceProductNum.value = Number(props.supplierFormInfo?.productNum);
    headerRightFormState.productUnit = props.supplierFormInfo?.unit || '';
    sourceProductUnit.value = props.supplierFormInfo?.unit || '';
  });
  const productNumLoading = ref(false);

  // 编辑产品信息 数量
  function editProductNumReq() {
    if (Number(headerRightFormState.productNum) <= 0) {
      headerRightFormState.productNum = sourceProductNum.value;
      createMessage.error('产品数量需大于0');
      return;
    }
    if (headerRightFormState.productNum == sourceProductNum.value) {
      return;
    }
    editProductInfoReq();
  }

  // 编辑产品信息 单位
  function editProductUnitReq() {
    if (!headerRightFormState.productUnit) {
      createMessage.error('请选择单位');
      return;
    }
    if (headerRightFormState.productUnit == sourceProductUnit.value) {
      return;
    }
    editProductInfoReq();
  }

  async function editProductInfoReq() {
    try {
      productNumLoading.value = true;
      const params = {
        formNo: formNo,
        productNum: Number(headerRightFormState.productNum),
        unit: headerRightFormState.productUnit
      };
      await editProductNum(params);
      // NOTE 更新原始产物数量值
      sourceProductNum.value = headerRightFormState.productNum;
      sourceProductUnit.value = headerRightFormState.productUnit;
      productNumLoading.value = false;
      createMessage.success('更新零部件数量/单位成功！');
    } catch (error) {
      console.log('error', error);
      headerRightFormState.productNum = sourceProductNum.value;
      headerRightFormState.productUnit = sourceProductUnit.value;
      productNumLoading.value = false;
    }
  }

  return {
    headerRightFormState,
    productNumLoading,
    editProductNumReq,
    editProductUnitReq
  };
};
